from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import asyncio
import logging

from shared.config import settings
from api.routes import health, convert

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 创建 FastAPI 应用
app = FastAPI(
    title=settings.api_title,
    version=settings.api_version,
    description="Convert Markdown to PowerPoint presentations via API",
    docs_url="/docs",
    redoc_url="/redoc"
)

# 添加 CORS 中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(health.router, tags=["Health"])
app.include_router(convert.router, prefix="/api/v1", tags=["Convert"])

# 全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
    logger.error(f"Global exception: {exc}")
    return JSONResponse(
        status_code=500,
        content={
            "success": False,
            "message": "Internal server error",
            "error_code": "INTERNAL_ERROR"
        }
    )

# 启动事件
@app.on_event("startup")
async def startup_event():
    logger.info(f"Starting {settings.api_title} v{settings.api_version}")
    logger.info(f"Storage path: {settings.storage_path}")
    
    # 创建存储目录
    settings.storage_path.mkdir(parents=True, exist_ok=True)
    
    # 启动清理任务
    asyncio.create_task(periodic_cleanup())

# 关闭事件
@app.on_event("shutdown")
async def shutdown_event():
    logger.info("Shutting down MD2PPT API")

# 定期清理任务
async def periodic_cleanup():
    """定期清理过期文件"""
    while True:
        try:
            from shared.storage import StorageManager
            storage_manager = StorageManager(settings.storage_path, settings.file_ttl)
            count = await storage_manager.cleanup_expired()
            if count > 0:
                logger.info(f"Cleaned up {count} expired files")
        except Exception as e:
            logger.error(f"Cleanup error: {e}")
        
        # 每小时清理一次
        await asyncio.sleep(3600)


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "api.app:app",
        host=settings.api_host,
        port=settings.api_port,
        reload=True
    )